<template>
  <div class="product-form">
    <h3>新增产品档案</h3>
    <el-form :model="formData" :rules="formRules" ref="formRef">
      <!-- 产品基本信息行 -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="产品编码" prop="cp_code">
            <el-input v-model="formData.cp_code" placeholder="请输入产品编码" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12"></el-col>
        <el-col :span="6">
          <el-form-item label="产品名称" prop="cp_name">
            <el-input v-model="formData.cp_name" placeholder="请输入产品名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 产品品牌和分类行 -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="产品品牌" prop="pp_code">
            <el-input v-model="formData.pp_code" placeholder="请选择产品品牌" @click="togglePPMTK" />
          </el-form-item>
        </el-col>
        <el-col :span="12"></el-col>
        <el-col :span="6">
          <el-form-item label="产品分类" prop="cp_fl">
            <el-select v-model="formData.cp_fl" placeholder="请选择产品分类">
              <el-option v-for="type in cpfl" :key="type.dictionary_id" :label="type.dictionary_name"
                         :value="type.dictionary_id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 产品型号和单位行 -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="产品型号" prop="cp_xh">
            <el-input v-model="formData.cp_xh" placeholder="请输入产品型号" />
          </el-form-item>
        </el-col>
        <el-col :span="12"></el-col>
        <el-col :span="6">
          <el-form-item label="产品单位" prop="dw_code">
            <el-select v-model="formData.dw_code" placeholder="请选择产品单位">
              <el-option v-for="type in dwOptions" :key="type.dw_code" :label="type.dw_name" :value="type.dw_code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 选择BOM和产品类型行 -->
      <el-row>
        <el-col :span="6">
          <el-form-item label="选择BOM" prop="bom_code">
            <el-select 
                v-model="formData.bom_code" 
                placeholder="请选择BOM" 
              >
                <el-option
                  v-for="item in bomdata"
                  :key="item.bom_code"
                  :label="item.bom_name"
                  :value="item.bom_code"
                />
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12"></el-col>
        <el-col :span="6">
          <el-form-item label="产品类型" prop="cp_lx">
            <el-select v-model="formData.cp_lx" placeholder="请选择产品类型">
              <el-option v-for="type in cplx" :key="type.dictionary_id" :label="type.dictionary_name"
                         :value="type.dictionary_id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <h3>产品属性</h3>
      <el-table :data="formData.attributes" border>
        <el-table-column prop="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="attributeName" label="属性名称">
          <template #default="{ row }">
            <el-select 
                v-model="row.attributeName" 
                placeholder="选择属性名称" 
                style="width: 200px"
                @change="handleLeaderChange"
              >
                <el-option
                  v-for="item in mcdata"
                  :key="item.sx_name"
                  :label="item.sx_name"
                  :value="item.sx_name"
                  @click="cxkc(row)"
                />
              </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="attributeValue" label="属性值">
          <template #default="{ row }">
            <el-select v-model="row.attributeValue" placeholder="请选择属性值">
              <el-option
                  v-for="item in row.sxdata"
                  :key="item.sx_code"
                  :label="item.sx_zhi"
                  :value="item.sx_code"
                />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="text" @click="removeItem('attributes', row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="addItem('attributes')">添加属性</el-button>

      <h3>产品文档</h3>
      <el-table :data="formData.documents" border>
        <el-table-column prop="index" label="序号" width="80"></el-table-column>
        <el-table-column label="文档名称">
          <template #default="{ row }">
            <el-input v-model="row.documentName" placeholder="请输入文档名称" />
          </template>
        </el-table-column>
        <el-table-column label="文档链接">
          <template #default="{ row }">
            <el-upload 
                       :on-success="(response) => handleUploadSuccess(response, row)" :on-error="handleUploadError"
                       :before-upload="beforeUpload" :file-list="row.fileList" :limit="5" action="/api/BD_CPSX/Upload">
              <el-button size="small" type="primary">点击上传文件</el-button>
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="text" @click="removeItem('documents', row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="addItem('documents')">添加文档</el-button>

      <h3>产品图片</h3>
      <el-table :data="formData.images" border>
        <el-table-column prop="index" label="序号" width="80"></el-table-column>
        <el-table-column label="图片名称">
          <template #default="{ row }">
            <el-input v-model="row.imageName" placeholder="请输入图片名称" />
          </template>
        </el-table-column>
        <el-table-column label="图片链接">
          <template #default="{ row }">
            <el-upload 
                      :on-success="(response) => handleUploadSuccess1(response, row)" :on-error="handleUploadError"
                       :before-upload="beforeUpload" :file-list="row.fileList" :limit="5" action="/api/BD_CPSX/Upload">
              <el-button size="small" type="primary">点击上传文件</el-button>
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="text" @click="removeItem('images', row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="addItem('images')">添加图片</el-button>

      <el-row justify="end" style="margin-top: 20px;">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </el-row>
    </el-form>
    <el-dialog v-model="isPPMTKVisible" title="选择品牌"
               style="height: 700px; width: 600px; background-color: #fff; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,0.15); border-radius: 30px;">
      <PPMTK @selection-confirmed="handleSelectionConfirmed" @cancel-selection="handleCancelSelection"></PPMTK>
    </el-dialog>
  </div>
</template>

<script>
import { ref, defineComponent, onMounted, watch,computed,reactive } from 'vue';
import { ElMessage, ElForm } from 'element-plus';
import axios from 'axios';
import PPMTK from '../MTK/PPMTK.vue';

export default defineComponent({
  components: { PPMTK },
  setup() {
    // 控制品牌选择弹窗的显示与隐藏
    const isPPMTKVisible = ref(false);
    const mcdata = ref([]);
    const sxdata = ref([]);
    const bomdata = ref([]);
    //生成编码
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
    const day = String(now.getDate()).padStart(2, '0'); // 补零
      
    // 生成四位随机数
    const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数
      
    // 拼接时间字符串和随机数
    const formattedTime = `${year}${month}${day}`;
    let id=`cp${formattedTime}${randomNumber}`
    //获取登录角色数据
    const uid=computed(()=>{
             return sessionStorage.getItem('u');
      })
      let yhid=reactive({
              id:uid
      })
    // 表单数据
    const formData = ref({
      cp_code: id,
      cp_name: '',
      pp_code: '',
      pp_name: '',
      cp_fl: '',
      cp_xh: '',
      dw_code: '',
      bom_code: '',
      cp_lx: '',
      cp_lxname: '',
      update_by: yhid.id,
      documents: [],
      images: [],
      attributes: []
    });
    // 表单验证规则
    const formRules = {
      cp_code: [
        { required: true, message: '请输入产品编码', trigger: 'blur' },
        // 可以添加更多验证规则，如正则表达式验证等
      ],
      cp_name: [
        { required: true, message: '请输入产品名称', trigger: 'blur' }
      ],
      cp_fl: [
        { required: true, message: '请选择产品分类', trigger: 'change' }
      ],
      dw_code: [
        { required: true, message: '请选择产品单位', trigger: 'change' }
      ],
      cp_lx: [
        { required: true, message: '请选择产品类型', trigger: 'change' }
      ]
    };
    // 表单引用
    const formRef = ref(null);
    // 产品单位选项
    const dwOptions = ref([]);
    // 产品分类选项
    const cpfl = ref([]);
    // 产品类型选项
    const cplx = ref([]);
    // 属性值选项
    const attributeValues = ref([]);

    // 获取产品单位、分类和类型数据
    const fetchData = async () => {
      try {
        const [dwResponse, cpflResponse, cplxResponse] = await Promise.all([
          axios.get('/api/DW/GetOneDW'),
          axios.get('/api/Dict/GetOneDict?id=7'),
          axios.get('/api/Dict/GetOneDict?id=9')
        ]);
        dwOptions.value = dwResponse.data;
        cpfl.value = cpflResponse.data;
        cplx.value = cplxResponse.data;
        const mc=await axios.get('/api/BD_CPSX/GetBD_CPSXFZ')
        mcdata.value=mc.data
        const bom=await axios.get('/api/Mbd_BOM/GetMbd_BOM')
        bomdata.value=bom.data
      } catch (error) {
        console.error('数据获取失败:', error);
        ElMessage.error('数据获取失败');
      }
    };

    // 添加项到指定集合
    const addItem = (collectionType) => {
      const newItem = {
        index: (formData.value[collectionType] || []).length + 1,
        attributeName: '',
        attributeValue: '',
        documentName: '',
        documentLink: '',
        imageName: '',
        imageLink: '',
        fileList: []
      };
      formData.value[collectionType].push(newItem);
    };

    // 从集合中移除指定项
    const removeItem = (collectionType, row) => {
      const index = formData.value[collectionType].findIndex(item => item === row);
      if (index!== -1) {
        formData.value[collectionType].splice(index, 1);
        if(row.attributeName!=''){
          mcdata.value.push({
            sx_name:row.attributeName
          })
        }
      }
    };

    // 处理品牌选择确认事件
    const handleSelectionConfirmed = (ids) => {
      formData.value.pp_code = ids;
      console.log("选择的 ID:", formData.value.pp_code);
      isPPMTKVisible.value = false;
    };

    // 处理品牌选择取消事件
    const handleCancelSelection = () => {
      isPPMTKVisible.value = false;
      console.log("已取消选择，隐藏 PPMTK");
    };

    // 切换品牌选择弹窗的显示状态
    const togglePPMTK = () => {
      isPPMTKVisible.value =!isPPMTKVisible.value;
    };

    // 处理文件上传成功事件
    const handleUploadSuccess = (response, row) => {
      row.documentLink=response
    };
    // 处理文件上传成功事件
    const handleUploadSuccess1 = (response, row) => {
      console.log(response)
      row.imageLink=response
    };
    // 处理文件上传失败事件
    const handleUploadError = (err) => {
      console.error('上传失败:', err);
      ElMessage.error('上传失败');
    };

    // 上传前检查文件大小
    const beforeUpload = (file,res) => {
      console.log(res)
      const isValid = file.size < 1024 * 1024;
      if (!isValid) {
        ElMessage.error('文件大小不能超过1MB！');
      }
      return isValid;
    };

    // 保存表单数据
    const save = async () => {
      try {
        console.log(formData.value);
        const response=await axios.post('/api/BD_CP/InsertCP',{
          cp_code:formData.value.cp_code,
          cp_name:formData.value.cp_name,
          pp_code:formData.value.pp_code[0],
          cp_fl:formData.value.cp_fl,
          cp_xh:formData.value.cp_xh,
          dw_code:formData.value.dw_code,
          cp_lx:formData.value.cp_lx,
          bom_code:formData.value.bom_code,
          update_by:formData.value.update_by
        });
        if(response.data){
          let sf=reactive(false)
          for(const team of formData.value.attributes){
            const response=await axios.post('/api/BD_CPSX/PostBD_CPSX',{
              cpsx_code:team.attributeValue,
              cp_code:formData.value.cp_code
            });
            sf=response.data
          }
          if(sf){
            let sf1=reactive(false)
            for(const team of formData.value.documents){
              //生成编码
              const now = new Date();
              const year = now.getFullYear();
              const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
              const day = String(now.getDate()).padStart(2, '0'); // 补零
                
              // 生成四位随机数
              const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数
                
              // 拼接时间字符串和随机数
              const formattedTime = `${year}${month}${day}`;
              let id=`cpwd${formattedTime}${randomNumber}`
              const response=await axios.post('/api/BD_CPWD/PostBD_CPWD',{
                cpwd_code: id,
                cpwd_name: team.documentName,
                cpwd_lb: team.documentLink,
                cp_code: formData.value.cp_code
              });
              sf1=response.data
            }
            if(sf1){
              let sf2=reactive(false)
              for(const team of formData.value.images){
                //生成编码
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
                const day = String(now.getDate()).padStart(2, '0'); // 补零
                  
                // 生成四位随机数
                const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数
                  
                // 拼接时间字符串和随机数
                const formattedTime = `${year}${month}${day}`;
                let id=`cptp${formattedTime}${randomNumber}`
                const response=await axios.post('/api/BD_CPTP/AddCPTP',{
                  cptp_code: id,
                  cptp_name: team.imageName,
                  cptp_zhi: team.imageLink,
                  cp_code: formData.value.cp_code
                });
                sf2=response.data
              }
              if(sf2>0){
                ElMessage.success('保存成功');
              }
            }
          }
        }
        
        // 保存成功后可以清空表单
        formData.value = {
          cp_code: '',
          cp_name: '',
          pp_code: '',
          pp_name: '',
          cp_fl: '',
          cp_xh: '',
          dw_code: '',
          bom_code: '',
          cp_lx: '',
          cp_lxname: '',
          update_by: '',
          documents: [],
          images: [],
          attributes: []
        };
        if (formRef.value) {
          formRef.value.resetFields();
        }
      } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败');
      }
    };

    // 提交表单前进行验证
    const submitForm = () => {
      console.log(formData)
      if (formRef.value) {
        formRef.value.validate((valid) => {
          if (valid) {
            save();
          } else {
            ElMessage.error('请检查表单输入');
            return false;
          }
        });
      }
    };
    async function cxkc(row){
      const response=await axios.get('/api/BD_CPSX/GetBD_CPSX?name='+row.attributeName)
      row.sxdata=response.data
      console.log(formData.value.attributes)
      const mc=await axios.get('/api/BD_CPSX/GetBD_CPSXFZ')
      mcdata.value=mc.data
      for(const team of formData.value.attributes){
        const index = mcdata.value.findIndex(item => item.sx_name === team.attributeName);
        if (index !== -1) {
          mcdata.value.splice(index, 1);
        }
      }
    }
    // 取消操作
    const cancel = () => {
      // 取消逻辑（例如，导航返回产品列表）
    };

    // 组件挂载时获取数据
    onMounted(() => {
      fetchData();
    });

    return {
      formData,
      formRules,
      formRef,
      dwOptions,
      cpfl,
      cplx,
      attributeValues,
      addItem,
      removeItem,
      save,
      cancel,
      handleUploadSuccess,
      handleUploadError,
      beforeUpload,
      isPPMTKVisible,
      togglePPMTK,
      handleSelectionConfirmed,
      handleCancelSelection,
      submitForm,
      mcdata,
      bomdata,
      sxdata,
      cxkc,
      handleUploadSuccess1
    };
  },
});
</script>

<style scoped>
.product-form {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.el-form {
  flex: 1;
  overflow-y: auto;
}
.eltable {
  height: 95%;
  background-color: rgba(255, 255, 255, 0.6); /* 设置表格背景色为白色，并带有50%的透明度 */
  backdrop-filter: blur(5px); /* 添加毛玻璃效果，增强透明感 */
}

</style>